package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.listener.BtyCwHpListener;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.core.util.LogUtil;
import cn.stylefeng.guns.sys.modular.rest.service.NameRelationService;
import cn.stylefeng.guns.sys.modular.system.entity.BtyCwHuopei;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyCwHuopeiMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.YybbMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyCwHuopeiParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyCwHpDto;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyCwHuopeiResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyCwHuopeiService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.excel.EasyExcel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 货赔表控制器
 *
 * @author 
 * @Date 2021-11-02 09:26:41
 */
@Controller
@RequestMapping("/btyCwHuopei")
public class BtyCwHuopeiController extends BaseController {

    private String PREFIX = "/modular/system/btyCwHuopei";

    @Autowired
    private BtyCwHuopeiService btyCwHuopeiService;
    @Autowired
    private BtyCwHuopeiMapper btyCwHuopeiMapper;
    @Autowired
    private YybbMapper yybbMapper;
    @Autowired
    private NameRelationService nameRelationService;

    /**
     * 跳转到主页面
     *
     * @author 
     * @Date 2021-11-02
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/btyCwHuopei.html";
    }

    /**
     * 新增页面
     *
     * @author 
     * @Date 2021-11-02
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyCwHuopei_add.html";
    }

    /**
     * 编辑页面
     *
     * @author 
     * @Date 2021-11-02
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyCwHuopei_edit.html";
    }

    /**
     * 新增接口
     *
     * @author 
     * @Date 2021-11-02
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyCwHuopeiParam btyCwHuopeiParam) {
        this.btyCwHuopeiService.add(btyCwHuopeiParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author 
     * @Date 2021-11-02
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyCwHuopeiParam btyCwHuopeiParam) {
        this.btyCwHuopeiService.update(btyCwHuopeiParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author 
     * @Date 2021-11-02
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyCwHuopeiParam btyCwHuopeiParam) {
        this.btyCwHuopeiService.delete(btyCwHuopeiParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author 
     * @Date 2021-11-02
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyCwHuopeiParam btyCwHuopeiParam) {
        BtyCwHuopei detail = this.btyCwHuopeiService.getById(btyCwHuopeiParam.getHuopeiId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author 
     * @Date 2021-11-02
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyCwHuopeiParam btyCwHuopeiParam, String date, Long provinceId, Long cityId) {
//        return this.btyCwHuopeiService.findPageBySpec(btyCwHuopeiParam, date);//手动分页
        return this.btyCwHuopeiService.hpList(btyCwHuopeiParam, date, provinceId, cityId);
    }

    /**
     * 导出列表
     *
     * @author
     */
    @ResponseBody
    @RequestMapping("/export")
    public List<BtyCwHuopeiResult> export(String date) {
        return this.btyCwHuopeiService.exportList(date);
    }

    /**
     * 导入excel
     */
    @RequestMapping("/import")
    @ResponseBody
    public Object batchImport(@RequestParam("file") MultipartFile file) {

        String fileName = file.getOriginalFilename();//文件名
        Boolean flag;
        JsonResult jsonResult = new JsonResult();
        try {
            flag = btyCwHuopeiService.batchImport(fileName, file);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return flag;

    }

    /**
     * 跳转到各店展示页面
     *
     */
    @RequestMapping("/hpDetail")
    public String hpDetail(Model model, BtyCwHuopei btyCwHuopei, String date) {

        Map map = btyCwHuopeiMapper.hpDetail(btyCwHuopei, date);

        //营业额为空
        if (ToolUtil.isEmpty(map.get("turnover"))){
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            String dateSdf = sdf.format(btyCwHuopei.getBeginTime()).substring(0, 7);

            //获取营业额
//            BigDecimal turnover = yybbMapper.getYye(btyCwHuopei.getShopName(), dateSdf);
            BigDecimal turnover = yybbMapper.getYye(btyCwHuopei.getShopName(), btyCwHuopei.getBeginTime(), btyCwHuopei.getEndTime());
            if (turnover == null){
                turnover = BigDecimal.ZERO;
            }
            turnover.setScale(2, BigDecimal.ROUND_HALF_UP);//截取两位
            BigDecimal five = turnover.multiply(new BigDecimal(0.0005)).setScale(2, BigDecimal.ROUND_HALF_UP);//营业额万分之五
            model.addAttribute("turnover",String.valueOf(turnover));//营业额
            model.addAttribute("five",String.valueOf(five));//营业额万分之五
        }else {
            model.addAttribute("turnover",map.get("turnover"));//营业额
            model.addAttribute("five",map.get("five"));//营业额万分之五
        }

        String beginTime = map.get("begin_time").toString();
        String endTime = map.get("end_time").toString();

        model.addAttribute("beginTime", beginTime);//开始时间
        model.addAttribute("endTime", endTime);//结束时间
        model.addAttribute("shopCode", map.get("shop_code"));//门店编号
        model.addAttribute("shopName", map.get("shop_name"));//门店名称


        return PREFIX + "/hpDetail.html";
    }

    /**
     * 各门店货赔详细信息
     *
     */
    @RequestMapping("/huopeiInfo")
    @ResponseBody
    public LayuiPageInfo huopeiInfo(BtyCwHuopei btyCwHuopei, String date) {
        //查询列表数据
        List<BtyCwHuopei> huopeiList = new ArrayList<>();
        //获取数据库看有没有营业额
        BtyCwHuopei cwHuopei = btyCwHuopeiMapper.getTurn(btyCwHuopei, date);
        //有数据 直接获取列表
        if (ToolUtil.isNotEmpty(cwHuopei.getTurnover())){
            huopeiList = this.btyCwHuopeiService.exportHuopei(btyCwHuopei, date);
            //计算
        }else {
            huopeiList = this.btyCwHuopeiService.getHuopei(btyCwHuopei,date);
        }
//        List<BtyCwHuopei> huopeiList = this.btyCwHuopeiService.getHuopei(btyCwHuopei,date);
        int total = huopeiList.size();
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(huopeiList);
        layuiPageInfo.setCount(total);
        return layuiPageInfo;
    }

    /**
     * 导出excel
     * app - 各门店货赔详细信息
     */
    @RequestMapping("/listExport")
    public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response,
                                              String shopName, Date beginTime, String shopCode, String date, Date endTime) {
//        shopName = java.net.URLDecoder.decode(shopName);
        return this.btyCwHuopeiService.exportExcel(request, response, shopName, beginTime, shopCode, date, endTime);
    }

    /**
     * 导出excel
     * pc - 各门店货赔详细信息
     */
    @RequestMapping("/exportHp")
    public ResponseEntity<byte[]> exportHp(HttpServletRequest request, HttpServletResponse response,
                                              String shopName, Date beginTime, String shopCode, String date, Date endTime) {
        return this.btyCwHuopeiService.exportHp(request, response, shopName, beginTime, shopCode, date, endTime);
    }

    /**
     * 编辑接口
     *
     */
    @RequestMapping("/editHuopei")
    @ResponseBody
    public ResponseData editHuopei(BtyCwHuopei btyCwHuopei) {
        this.btyCwHuopeiService.editHuopei(btyCwHuopei);
        return ResponseData.success();
    }

    /**
     * app查询-各门店货赔详细信息
     *
     */
    @ResponseBody
    @RequestMapping(value = "/huopeiDate", method = RequestMethod.GET)
    public ResponseData huopeiDate(BtyCwHuopei btyCwHuopei, String date) {

        if (StringUtils.isBlank(btyCwHuopei.getShopName())) {
            return ResponseData.error(412, "请求失败，店名不能为空");
        }
        if (ToolUtil.isEmpty(date)) {
            return ResponseData.error(412, "请求失败，业务日期不能为空");
        }

        //获取该店发送状态
        Integer sta = btyCwHuopeiMapper.getSta(btyCwHuopei, date);

        if (ToolUtil.isEmpty(sta) || sta == 0){//未发送门店
            return ResponseData.success(new ArrayList<BtyCwHuopei>());
        }else if (sta == 1){//已发送门店
            List<BtyCwHuopei> detail = new ArrayList<>();
            //获取数据库看有没有营业额
            BtyCwHuopei cwHuopei = btyCwHuopeiMapper.getTurn(btyCwHuopei, date);
            //有数据 直接获取列表
            if (ToolUtil.isNotEmpty(cwHuopei) && ToolUtil.isNotEmpty(cwHuopei.getTurnover())){
                detail = this.btyCwHuopeiService.exportHuopei(btyCwHuopei, date);
                //计算
            }else {
                detail = this.btyCwHuopeiService.getHuopei(btyCwHuopei, date);
            }
            return ResponseData.success(detail);
        }
        return ResponseData.success();
    }

    /**
     * 获取店名列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/dmList")
    public List dmList() {
        return btyCwHuopeiService.dmList();
    }

    /**
     * 同步酒水卖价
     * @return
     */
    @ResponseBody
    @RequestMapping("/editJsmj")
    public ResponseData editJsmj(String date) {
        return btyCwHuopeiService.editJsmj(date);
    }

    /**
     * 同步货赔单价(批量)
     * @return
     */
    @ResponseBody
    @RequestMapping("/editPrice")
    public ResponseData editPrice(String date) {
        return btyCwHuopeiService.editPrice(date);
    }

    /**
     * 同步单店酒水价格
     * @return
     */
    @ResponseBody
    @RequestMapping("/editDdjs")
    public ResponseData editDdjs(String date, String shopCode) {
        return btyCwHuopeiService.editDdjs(date, shopCode);
    }

    /**
     * 同步单店货赔价格
     * @return
     */
    @ResponseBody
    @RequestMapping("/editDdhp")
    public ResponseData editDdhp(String date, String shopCode) {
        return btyCwHuopeiService.editDdhp(date, shopCode);
    }

    /**
     * 计算货赔合计
     * @return
     */
    @ResponseBody
    @RequestMapping("/editHp")
    public ResponseData editHp(String date) {
        return btyCwHuopeiService.editHp(date);
    }

    /**
     * 获取省列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/cityList")
    public ResponseData cityList(){
        return btyCwHuopeiService.cityList();
    }

    /**
     * 获取市列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/cityNameList")
    public ResponseData cityNameList(Long pid){
        return btyCwHuopeiService.cityNameList(pid);
    }

    /**
     * 导入excel
     */
    @RequestMapping("/addUsers")
    @ResponseBody
    public Object addUsers(@RequestParam("file") MultipartFile file) {
        JsonResult jsonResult = new JsonResult();
        try {
            BtyCwHpListener btyCwHpListener = new BtyCwHpListener(btyCwHuopeiService);
            EasyExcel.read(file.getInputStream(), BtyCwHpDto.class, btyCwHpListener).sheet(0).doRead();
        }catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return true;
    }

    /**
     * 发送门店
     * @return
     */
    @ResponseBody
    @RequestMapping("/sendMsg")
    public ResponseData sendMsg(String date, Long provinceId, Long cityId){
        return btyCwHuopeiService.sendMsg(date, provinceId, cityId);
    }

    /**
     * 获取供应链店名
     * @return
     */
    @ResponseBody
    @RequestMapping("/scmName")
    public ResponseData scmName(){
//        List<Map<String,String>> list = LogUtil.getStore();
//        List<Map<String,String>> nameList = new ArrayList<>();//展示天财供应链店名
//        if (ToolUtil.isNotEmpty(list)){
//            nameList = list.stream().filter(w -> w.get("externalType").equals("1")).collect(Collectors.toList());
//        }else {
//            nameList = nameRelationService.getName();
//        }

        List<Map<String,String>> nameList = nameRelationService.getName();
        if (ToolUtil.isEmpty(nameList)){
            nameList = LogUtil.getStore().stream().filter(w -> w.get("externalType").equals("1")).collect(Collectors.toList());
        }

        return ResponseData.success(nameList);
    }

    /**
     * 获取供应链货赔详情
     * @return
     */
    @ResponseBody
    @RequestMapping("/scmDetail")
    public ResponseData scmDetail(@RequestParam(value = "storeIdList",required = false) List<String> storeIdList, String startTime, String endTime){
        if (ToolUtil.isEmpty(startTime)){
            return ResponseData.error("请选择开始日期！");
        }
        if (ToolUtil.isEmpty(endTime)){
            return ResponseData.error("请选择结束日期！");
        }
        if (ToolUtil.isEmpty(storeIdList)){
            //获取storeIdList
            storeIdList = nameRelationService.getStoreIdList();
            for(int i = 0; i < storeIdList.size();){
                int i2 = (i + 260);
                i2 = i2 > storeIdList.size() ? storeIdList.size() : i2;
                List<String> sub = storeIdList.subList(i, i2);
                btyCwHuopeiService.scmDetail(sub, startTime, endTime);
                i = i2;
            }
        }else {
            btyCwHuopeiService.scmDetail(storeIdList, startTime, endTime);
        }
        return ResponseData.success();
    }


    /**
     * 批量导出excel
     * pc - 各门店货赔详细信息
     */
    @RequestMapping("/exportBatch")
    public ResponseEntity<byte[]> exportBatch(HttpServletRequest request, HttpServletResponse response, String date) {
        return this.btyCwHuopeiService.exportBatch(request, response, date);
    }
}


